package com.devicemantra.coordinate;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet 
{
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException 
	{
	try {
	ServletFileUpload upload = new ServletFileUpload();
	upload.setSizeMax(500000);
	System.out.println("Started upload servlet");
	//res.setContentType("text/plain");
	//res.setContentType("img/jpeg");
	PrintWriter out = res.getWriter();

	try {
	FileItemIterator iterator = upload.getItemIterator(req);
	while (iterator.hasNext()) {
	FileItemStream item = iterator.next();
	InputStream in = item.openStream();
	
	if (item.isFormField()) {
	//out.println("Got a form field: " + item.getFieldName());
	} else {
	String fieldName = item.getFieldName();
	String fileName = item.getName();
	String contentType = item.getContentType();

	/*out.println("--------------");
	out.println("fileName = " + fileName);
	out.println("field name = " + fieldName);
	out.println("contentType = " + contentType); */

	String fileContents = null;
	try {
	 fileContents = IOUtils.toString(in);
	// out.println("lenght: " + fileContents.length());
	 //out.println(fileContents);
	 out.println("<script language=\"javascript\" type=\"text/javascript\">alert(\"Amith here\");</script>");
	} finally {
	 IOUtils.closeQuietly(in);
	}

	}
	}
	} catch (SizeLimitExceededException e) {
	/*out.println("You exceeded the maximu size ("
	+ e.getPermittedSize() + ") of the file ("
	+ e.getActualSize() + ")"); */
	}
	} catch (Exception ex) {

	throw new ServletException(ex);
	}
	}
}
